/**
 * Copyright (c) 2009 Andrew Rapp. All rights reserved.
 *
 * This file is part of XBee-Arduino.
 *
 * XBee-Arduino is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XBee-Arduino is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <XBee.h>

#include <SD.h>

/*
This example is for Series 2 XBee
 Receives a ZB RX packet and sets a PWM value based on packet data.
 Error led is flashed if an unexpected packet is received
 */

XBee xbee = XBee();
XBeeResponse response = XBeeResponse();
// create reusable response objects for responses we expect to handle 
ZBRxResponse rx = ZBRxResponse();
ModemStatusResponse msr = ModemStatusResponse();

int statusLed = 13;
int errorLed = 13;
int dataLed = 13;

const int chipSelect = 4;

void flashLed(int pin, int times, int wait) {

  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    delay(wait);
    digitalWrite(pin, LOW);

    if (i + 1 < times) {
      delay(wait);
    }
  }
}

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  pinMode(dataLed,  OUTPUT);

  initSd();
  // start serial
  xbee.begin(9600);
  delay(5000);

  flashLed(statusLed, 3, 50);
}

boolean initSd()
{
  boolean result = true;

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    result = false;
  }
  else{
    logData("card initialized.");
  }
  return result;
}

void logData(String data)
{
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("debug3.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    int time = millis();
    //dataFile.print(time);
    dataFile.println(data);
    dataFile.close();
  }  
  // if the file isn't open, pop up an error:
  else {
    flashLed(statusLed, 1, 2000);
  } 
}

void logData(int data)
{
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("debug3.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    int time = millis();
    //dataFile.print(time);
    dataFile.println(data);
    dataFile.close();
  }  
  // if the file isn't open, pop up an error:
  else {
    flashLed(statusLed, 1, 2000);
  } 
}

// continuously reads packets, looking for ZB Receive or Modem Status
void loop() {


  xbee.readPacket();

  if (xbee.getResponse().isAvailable()) {
    // got something

    if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
      // got a zb rx packet

      // now fill our zb rx class
      xbee.getResponse().getZBRxResponse(rx);

      if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED) {
        // the sender got an ACK
        flashLed(statusLed, 10, 100);
        logData("the sender got an ACK");
      } 
      else {
        // we got it (obviously) but sender didn't get an ACK
        flashLed(errorLed, 2, 100);
        logData("we got it (obviously) but sender didn't get an ACK");
      }
      // get data from transmission
      logData("data received");
      logData(rx.getData(0));
      logData(rx.getData(1));
    } 
/*    else if (xbee.getResponse().getApiId() == MODEM_STATUS_RESPONSE) {
      xbee.getResponse().getModemStatusResponse(msr);
      // the local XBee sends this response on certain events, like association/dissociation

      if (msr.getStatus() == ASSOCIATED) {
        // yay this is great.  flash led
        flashLed(statusLed, 3, 100);
        logData("yay this is great.  flash led");
      } 
      else if (msr.getStatus() == DISASSOCIATED) {
        // this is awful.. flash led to show our discontent
        flashLed(errorLed, 10, 10);
        logData("this is awful.. flash led to show our discontent");
      } 
      else {
        // another status
        flashLed(statusLed, 5, 10);
        logData("we got it (obviously) but sender didn't get an ACK");
      }
    } 
    else {
      // not something we were expecting
      flashLed(errorLed, 1, 25);    
      logData("not something we were expecting");
    }
    */
  } 
  else if (xbee.getResponse().isError()) {
    String dataToLog = "Error reading packet.  Error code: " + xbee.getResponse().getErrorCode();
    logData(dataToLog);
  }
}



